package org.budo.dubbo.registry.redis.util;

import java.util.Iterator;
import java.util.List;

import org.budo.dubbo.registry.redis.BudoRedisRegistry;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;

/**
 * @author lmw
 */
public class DubboUrlUtil {
    public static String toCategoryPath(BudoRedisRegistry budoRedisRegistry, URL url) {
        String category = url.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY); // providers or consumers
        return budoRedisRegistry.getProtocol() + ":" + url.getServiceInterface() + Constants.PATH_SEPARATOR + category;
    }

    public static String toSimpleString(URL url) {
        return url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + Constants.PATH_SEPARATOR + url.getServiceInterface();
    }

    public static String toSimpleString(List<URL> urls) {
        if (null == urls) {
            return null;
        }

        Iterator<URL> iterator = urls.iterator();
        if (!iterator.hasNext()) {
            return "[]";
        }

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append('[');
        for (;;) {
            stringBuilder.append(toSimpleString(iterator.next()));
            if (!iterator.hasNext()) {
                return stringBuilder.append(']').toString();
            }
            stringBuilder.append(',').append(' ');
        }
    }
}